package seismosurfer.update;

import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import seismosurfer.data.CatalogData;
import seismosurfer.database.CatalogDAO;
import seismosurfer.database.DB;
import seismosurfer.util.SeismoException;
import seismosurfer.util.TimeUtil;

import com.bbn.openmap.util.Debug;

/**
 * Manages the update of the database with new data.
 * The new data come from the catalogs that are
 * stored in the CATALOG table. For each catalog
 * a deamon thread is created, that updates the
 * database.
 *
 */
public class UpdateService {
    
    /**
     * For each catalog in the db creates
     * a deamon thread that updates
     * the db from this catalog according
     * to the time periods specified in the db.
     *
     */
    public UpdateService() {

        DB.openConnection();
        CatalogDAO dao = new CatalogDAO();
        List result = dao.getCatalogs();
        DB.closeConnection();

        for (Iterator iter = result.iterator(); iter.hasNext();) {
            CatalogData item = (CatalogData) iter.next();
            if (item.isUpdatable()) {
                Timer timer = new Timer(true);
                Debug.output("Timer parameters:" + item.getDelay() + "\t"
                        + item.getPeriod());
                timer.schedule(new UpdateTask(item.getCatalogID()), item
                        .getDelay(), item.getPeriod());
            }

        }

    }
    
    /**
     * This task updates the db from 
     * a catalog.
     *
     */
    class UpdateTask extends TimerTask {
        int catalogID;

        public UpdateTask(int id) {
            catalogID = id;
        }
        
        /**
         * Opens a db connection, creates
         * an Updater object that updates the db
         * and closes the db connection.
         */
        public void run() {
            Debug.output("Running update task for catalog: " + catalogID);
            Debug.output("Task starting at: "
                    + TimeUtil.toText(System.currentTimeMillis()));

            try {
                DB.openConnection();
                Updater up = Updater.makeUpdater(catalogID);
                up.doUpdate();

                Debug.output("Task ending at:"
                        + TimeUtil.toText(System.currentTimeMillis()));
                DB.closeConnection();
            } catch (SeismoException e) {
                Debug.error("Error during update from catalog " + catalogID
                        + "\n" + e.getMessage());
            }
        }

    }

}
